package com.shjy.driver.activity;

import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.shjy.driver.R;
import com.shjy.driver.adapter.BlueToothDeviceAdapter;
import com.shjy.driver.base.BluetoothPrint;
import com.shjy.driver.util.AntUtils;
import com.shjy.driver.util.BusinesNumberConst;
import com.shjy.driver.util.ClsUtils;
import com.shjy.driver.widget.BlueToothConnectDialog;
import com.shjy.driver.widget.BlueToothConnectMessageDialog;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * Created by zmy on 2017/11/12.
 */

public class PrintActivity extends AppCompatActivity implements View.OnClickListener,AdapterView.OnItemClickListener{
    public static final String tag = PrintActivity.class.getSimpleName();
    protected ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(1,2,500, TimeUnit.MILLISECONDS,new ArrayBlockingQueue<Runnable>(5));


    public static final int REQUESTCODE_BLUETOOTH_ENABLE = 1;
    public static final int REQUESTCODE_BLUETOOTH_OPENSETTING = 2;

    private BluetoothAdapter bluetoothAdapter;

    private BluetoothDevice btDevice;
    private BluetoothSocket btSocket;

    private Set<BluetoothDevice> paredDevice;
    private List<BluetoothDevice> listDevice = new ArrayList<BluetoothDevice>();
    private BlueToothDeviceAdapter blueToothDeviceAdapter;

    private ListView listviewDevice;
    private BlueToothConnectDialog blueToothConnectDialog ;
    private BlueToothConnectMessageDialog blueToothConnectMessageDialog;

    private static final int WHAT_CONNECT_SUCCESS = 0x01;

    private static final int WHAT_CONNECT_FAILURE = 0x02;

    private static final int HANDLER_MSG_WHAT_CONN_FAIL = 404;

    private static final int HANDLER_MSG_WHAT_CONN_OFF = 0x04;

    private Handler blueToothHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case WHAT_CONNECT_SUCCESS:{

                    AntUtils.saveStringAttr(PrintActivity.this, BusinesNumberConst.CONN_BLUE_TOOTH_ADDR,listDevice.get(position).getAddress());
                    blueToothDeviceAdapter.setConnectPos(position);
                    blueToothDeviceAdapter.setSelectPos(position);
                    blueToothDeviceAdapter.notifyDataSetChanged();

//                    blueToothConnectDialog.dismiss();

                    AntUtils.sendNotification(PrintActivity.this, R.drawable.i_printer_statusbar,"打印机已绑定");
                    buttonConfirm.setText("打印测试");
                    buttonConfirm.setId(R.id.buttonPrintTest);
//                    blueToothConnectMessageDialog = new BlueToothConnectMessageDialog(PrintActivity.this,PrintActivity.this,"连接成功");
//                    blueToothConnectMessageDialog.show();
                    AlertDialog.Builder builder=new AlertDialog.Builder(PrintActivity.this);
                    builder.setTitle("信息");
                    builder.setIcon(R.mipmap.ic_launcher);
                    builder.setMessage("连接成功");
                    //setPositiveButton积极按钮
                    builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                        }
                    });
                    //setNegativeButton消极的
                    builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                        }
                    });
                    builder.setCancelable(false);
                    AlertDialog alertDialog=builder.create();
                    alertDialog.show();
                }break;
                case WHAT_CONNECT_FAILURE:{
//                    blueToothConnectDialog.dismiss();
//                    blueToothConnectMessageDialog = new BlueToothConnectMessageDialog(PrintActivity.this,PrintActivity.this,"连接失败");
//                    blueToothConnectMessageDialog.show();
                    AlertDialog.Builder builder=new AlertDialog.Builder(PrintActivity.this);
                    builder.setTitle("信息");
                    builder.setIcon(R.mipmap.ic_launcher);
                    builder.setMessage("连接失败");
                    //setPositiveButton积极按钮
                    builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                        }
                    });
                    //setNegativeButton消极的
                    builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                        }
                    });
                    builder.setCancelable(false);
                    AlertDialog alertDialog=builder.create();
                    alertDialog.show();
                }break;
                case HANDLER_MSG_WHAT_CONN_FAIL:{
                    AlertDialog.Builder builder=new AlertDialog.Builder(PrintActivity.this);
                    builder.setTitle("信息");
                    builder.setIcon(R.mipmap.ic_launcher);
                    builder.setMessage(msg.obj.toString());
                    //setPositiveButton积极按钮
                    builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                        }
                    });
                    //setNegativeButton消极的
                    builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                        }
                    });
                    builder.setCancelable(false);
                    AlertDialog alertDialog=builder.create();
                    alertDialog.show();
                    //showMessage(msg.obj.toString());
                }break;
                case HANDLER_MSG_WHAT_CONN_OFF:{
                    //showMessage("打印完成");
                }break;
            }
        }
    };

    public static final UUID MY_UUID = UUID
            .fromString("00001101-0000-1000-8000-00805F9B34FB");

    private ConnectThread mConnectThread;

    public PrintActivity() {
        // Required empty public constructor
    }


    Button buttonConfirm;

    class DiscoverBlueToothReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if(BluetoothDevice.ACTION_FOUND.equalsIgnoreCase(intent.getAction())){
                BluetoothDevice bluetoothDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                updateParedDevices(bluetoothDevice);
            }else if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(intent.getAction())){
                bluetoothAdapter.cancelDiscovery();
                context.unregisterReceiver(this);
                //baseFragmentHandler.sendEmptyMessage(HIDE_PROGRESS);
//                PrintActivity.this.unregisterReceiver(discoverBlueToothReceiver);
            }
        }
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // layout
        setContentView(R.layout.fragment_find_bluetooth_device);

        blueToothAddr = AntUtils.getStringAttr(PrintActivity.this,BusinesNumberConst.CONN_BLUE_TOOTH_ADDR);
        findViewById(R.id.buttonFind).setOnClickListener(this);
        findViewById(R.id.buttonBack).setOnClickListener(this);
        buttonConfirm = (Button) findViewById(R.id.buttonConfirm);
        buttonConfirm.setOnClickListener(this);
//        view.findViewById(R.id.buttonPrintTest).setOnClickListener(this);
        listviewDevice = (ListView) findViewById(R.id.listviewDevice);
        listviewDevice.setOnItemClickListener(this);
        initBluetooth();
        String blueAddr = AntUtils.getStringAttr(PrintActivity.this,BusinesNumberConst.CONN_BLUE_TOOTH_ADDR);
    }

    private String blueToothAddr;


    private void initBluetooth(){
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        blueToothDeviceAdapter = new BlueToothDeviceAdapter(PrintActivity.this,listDevice);
        blueToothConnectDialog = new BlueToothConnectDialog(PrintActivity.this,this);
    }
    private int position = -1;
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.buttonConfirm:{
                if(this.position == -1){
                    //Snackbar.make(v,"请选择设备",Snackbar.LENGTH_LONG).show();
                    return;
                }
                BluetoothDevice bluetoothDevice = listDevice.get(this.position);
                String info = bluetoothDevice.getAddress();
                String address = info.substring(info.length() - 17); //mac地址长度为17位，包括冒号

                connectBluetooth(address); //连接配对设备
                //baseFragmentHandler.sendMessage(blueToothHandler.obtainMessage(SHOW_PROGRESS,"蓝牙连接中..."));
                v.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        //baseFragmentHandler.sendEmptyMessage(HIDE_PROGRESS);
                    }
                },3000);
               /* blueToothConnectDialog.setSelectPos(position);
                blueToothConnectDialog.show();*/
            }break;
            case R.id.buttonPrintTest:{
                doPrintTest();
            }break;
            case R.id.buttonBack:{
                //carNumProvinceFragmentListener.handler(tag,v.getId());
                finish();
            }break;
            case R.id.buttonFind:{
                Toast toast = Toast.makeText(getApplicationContext(),
                        "开始搜索", Toast.LENGTH_LONG);
                toast.setGravity(Gravity.CENTER, 0, 0);
                toast.show();
                findDevice();
            }break;
            case R.id.buttonConnect:{
                Toast toast = Toast.makeText(getApplicationContext(),
                        "开始连接", Toast.LENGTH_LONG);
                toast.setGravity(Gravity.CENTER, 0, 0);
                toast.show();
                findDevice();
                int selectPos = blueToothConnectDialog.getSelectPos();
                BluetoothDevice bluetoothDevice = listDevice.get(selectPos);
                String info = bluetoothDevice.getAddress();
                String address = info.substring(info.length() - 17); //mac地址长度为17位，包括冒号

                connectBluetooth(address); //连接配对设备
            }break;
            case R.id.buttonDialogConfirm:{
                blueToothConnectMessageDialog.dismiss();
               /* int selectPos = blueToothConnectDialog.getSelectPos();
                if(selectPos == -1){
                    return;
                }
                String pwd = blueToothConnectDialog.getPassWord();
                BluetoothDevice bluetoothDevice = listDevice.get(selectPos);

                AntUtils.saveStringAttr(PrintActivity.this, BusinesNumberConst.CONN_BLUE_TOOTH_ADDR,bluetoothDevice.getAddress());
                blueToothDeviceAdapter.setConnectPos(selectPos);
                buttonConfirm.setText("打印测试");
                blueToothDeviceAdapter.setSelectPos(blueToothConnectDialog.getSelectPos());
                blueToothDeviceAdapter.notifyDataSetChanged();
                blueToothConnectDialog.setSelectPos(-1);
                blueToothConnectMessageDialog.dismiss();*/
            }break;
        }
    }

    /**
     * 请求打开蓝牙
     */
    private void requestOpenBluetooth() {
        Intent it = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); //请求打开蓝牙
        it.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300); //设置蓝牙可见性
        PrintActivity.this.startActivityForResult(it, REQUESTCODE_BLUETOOTH_ENABLE);
    }
    private IntentFilter intentFilter = new IntentFilter();
    private DiscoverBlueToothReceiver discoverBlueToothReceiver = new DiscoverBlueToothReceiver();
    private void findDevice(){
        if(!bluetoothAdapter.isEnabled()) {
            requestOpenBluetooth();
        } else {
            listviewDevice.setAdapter(blueToothDeviceAdapter);

            intentFilter.addAction(BluetoothDevice.ACTION_FOUND);
            intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
            PrintActivity.this.registerReceiver(discoverBlueToothReceiver,intentFilter);
            bluetoothAdapter.startDiscovery();
            //baseFragmentHandler.sendMessage(baseFragmentHandler.obtainMessage(SHOW_PROGRESS,"正在查找打印机..."));
        }
    }

    /**
     * 更新已配对列表
     */
    private void updateParedDevices() {

        paredDevice = bluetoothAdapter.getBondedDevices();
        if(paredDevice.size() > 0) {
            listDevice.clear();
            for(BluetoothDevice btDevice : paredDevice) {
                listDevice.add(btDevice);
            }
        }

        blueToothDeviceAdapter.notifyDataSetChanged();
    }

    private void updateParedDevices(BluetoothDevice bluetoothDevice){
        boolean isExist = false;
        for(BluetoothDevice device:listDevice){
            if(device.getAddress().equalsIgnoreCase(bluetoothDevice.getAddress())){
                isExist = true;
                continue;
            }
        }
        if(!isExist){
            btDevice = bluetoothDevice;
            listDevice.add(bluetoothDevice);
            if(bluetoothDevice.getAddress().equalsIgnoreCase(blueToothAddr)){
                int size = listDevice.size();
                blueToothDeviceAdapter.setConnectPos(size-1);
            }
        }
        blueToothDeviceAdapter.notifyDataSetChanged();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        this.position = position;

        String blueAddr = AntUtils.getStringAttr(PrintActivity.this,BusinesNumberConst.CONN_BLUE_TOOTH_ADDR);
        if(listDevice.get(position).getAddress().equalsIgnoreCase(blueAddr)){
            buttonConfirm.setText("打印测试");
            buttonConfirm.setId(R.id.buttonPrintTest);
        }else {
            buttonConfirm.setText("确定");
            buttonConfirm.setId(R.id.buttonConfirm);
        }
        blueToothDeviceAdapter.setSelectPos(position);
        blueToothDeviceAdapter.notifyDataSetChanged();
    }


    /**
     * 连接配对设备
     * @param address 设备MAC地址值
     */
    private synchronized void connectBluetooth(String address) {
        btDevice = bluetoothAdapter.getRemoteDevice(address);

        if(mConnectThread != null) {
            mConnectThread.cancel();
            mConnectThread = null;
        }

        mConnectThread = new ConnectThread(btDevice);
        mConnectThread.start();
    }

    private class ConnectThread extends Thread {
        //        private final BluetoothSocket mmSocket;
        private final BluetoothDevice mmDevice;
        private String TAG = "BluetoothPrintActivity_ConnectThread";

        public ConnectThread(BluetoothDevice device) {
            mmDevice = device;

            // Get a BluetoothSocket for a connection with the
            // given BluetoothDevice
            try {
                btSocket = mmDevice.createRfcommSocketToServiceRecord(MY_UUID);
            } catch (IOException e) {
            }
        }

        public void run() {
            setName("ConnectThread");

            // Make a connection to the BluetoothSocket
            try {

                if(btSocket == null || !btSocket.isConnected()) {
                    btSocket = mmDevice.createRfcommSocketToServiceRecord(MY_UUID);
                }

                // Always cancel discovery because it will slow down a connection
                bluetoothAdapter.cancelDiscovery();

                // This is a blocking call and will only return on a
                // successful connection or an exception

//                mmDevice.setPairingConfirmation(true);

                btSocket.connect();

                ClsUtils.setPin(mmDevice.getClass(), mmDevice, "1234"); // 手机和蓝牙采集器配对
                ClsUtils.createBond(mmDevice.getClass(), mmDevice);
            } catch (Exception e) {
                if(btSocket != null){
                    try {
                        btSocket.close();
                    } catch (IOException e2) {
                        e2.printStackTrace();
                    }
                }
                blueToothHandler.sendEmptyMessage(WHAT_CONNECT_FAILURE);
                /*Message msg = feeOverHandler.obtainMessage(ParkingFeeOverFragment.HANDLER_MSG_WHAT_CONN_FAIL,"蓝牙连接失败!");
                feeOverHandler.sendMessage(msg);*/
                // Start the service over to restart listening mode
//                BluetoothService.this.start();
                return;
            }

            /**
             * 显示连接状态，已连接设备名称
             */

            if(btSocket != null){
                try {
                    btSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
           /* Message msg = feeOverHandler.obtainMessage(ParkingFeeOverFragment.HANDLER_MSG_WHAT_DEVICE_NAME);
            Bundle bundle = new Bundle();
            bundle.putString(EXTRA_DEVICE_ADDRESS, mmDevice.getName());
            msg.setData(bundle);
            feeOverHandler.sendMessage(msg);*/
            blueToothHandler.sendEmptyMessage(WHAT_CONNECT_SUCCESS);
        }

        public void cancel() {
            try {
                btSocket.close();
//                mHandler.sendEmptyMessage(HANDLER_MSG_WHAT_CONN_OFF);
            } catch (IOException e) {
//                Log.e(TAG, "close() of connect socket failed", e);
            }
        }
    }
    private BluetoothPrint bluetoothPrint;
    private void doPrintTest(){
        blueToothAddr = AntUtils.getStringAttr(PrintActivity.this,BusinesNumberConst.CONN_BLUE_TOOTH_ADDR);
        if(TextUtils.isEmpty(blueToothAddr)){
            //showMessage("没有设置打印机,请到工具-打印机设置中去设置打印机!");
            return;
        }

        threadPoolExecutor.execute(new Runnable() {
            @Override
            public void run() {
                bluetoothPrint = new BluetoothPrint(PrintActivity.this,blueToothHandler,blueToothAddr);
                bluetoothPrint.connectedSend(getPrintTestContent());
            }
        });
    }

    private String  getPrintTestContent(){
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("\n");
        stringBuffer.append("*打印测试*");
        stringBuffer.append("\n");
        stringBuffer.append("*        *");
        stringBuffer.append("\n");
        stringBuffer.append("*欢迎使用*");
        stringBuffer.append("\n");
        stringBuffer.append("*上海交运便捷*");
        stringBuffer.append("\n");
        stringBuffer.append("*货运叫车APP*");
        stringBuffer.append("\n");
        stringBuffer.append("*上海交运便捷*");
        stringBuffer.append("\n");
        stringBuffer.append("*货运有限公司*");
        stringBuffer.append("\n");
        stringBuffer.append("*   版本号  *");
        stringBuffer.append("\n");
        stringBuffer.append("*"+AntUtils.getVersionName(this)+"*");
        stringBuffer.append("\n");
        stringBuffer.append("*********");
        stringBuffer.append("\n");
        return stringBuffer.toString();
    }
}
